package com.bi.design.pojo;


import com.bi.design.enums.GlobalResultEnum;
import com.bi.design.exception.GlobalException;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Data
@AllArgsConstructor
public class TokenTools {
    private String token;
    private Date createTime;
    public static Map<String, TokenTools> CACHE = new ConcurrentHashMap<>();

    public static void validateToken(String token) throws GlobalException {
        TokenTools tokenTools = CACHE.get(token);
        // 2个小时
        if (tokenTools == null || new Date().after(new Date(tokenTools.getCreateTime().getTime() + (1000 * 7200)))) {
            throw new GlobalException(GlobalResultEnum.TOKEN_EXPIRE);
        }
    }

    public static String saveToken() {
        String token = UUID.randomUUID().toString();
        TokenTools tokenTools = new TokenTools(token, new Date());
        CACHE.put(token, tokenTools);
        return token;
    }
}
